package io.gitee.yth.design.pattern.test.core.pattern.structural.proxy.jdkDynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author yth
 * @since 2023-04-27-23:27
 */
public class ProxyFactory {

    /**
     * 被代理的目标对象
     */
    private final Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        /*
         * @param   ClassLoader loader 指定当前目标对象使用的类加载器
         * @param   Class<?>[] interfaces 目标对象实现的接口类型
         * @param   InvocationHandler h 事件处理，执行目标对象的方法时，会触发事件处理器的方法
         * @return  代理对象
         */
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("--jdk proxy start--");
                        final Object retVal = method.invoke(target, args);
                        System.out.println("return = " + retVal);
                        System.out.println("--jdk proxy commit--");
                        if (retVal instanceof String)
                            return "Teacher " + retVal;
                        return retVal;
                    }
                }
        );
    }

}
